<?php
class TdForm extends TdComponent {
  var $method = "POST";
  var $action = ".";
  var $fields = array();
  var $name;
  var $errormessage;

  function __construct($id, $template="") {
    parent::__construct($id, $template);
    
    $this->setName($id);
  }

  function addField($field) {
  	$field->setForm($this);
    $this->fields[$field->id] = $field;    
  }
  
  function getField($id) {
  	return $this->fields[$id];
  }
  
  function __toString() {
  	$pout = parent::__toString();
  	if ($pout != "") {
  		return $pout;
  	}
  	
    ob_start();
   
    print("<form method=\"".$this->method."\" action=\"".$this->action."\" id=\"".$this->id."\" name=\"".$this->name."\">");
    print("<input type=\"hidden\" name=\"tdform\" value=\"".$this->id."\" />");
    foreach ($this->fields as $field) {
      print($field);
      if ($field->gotError()) {
      	print($field->getErrorMessage());
      }
    }
    print("</form>");

    return ob_get_clean();
  }
  
  function setMethod($value) {
    $this->method = $value;
  }
  
  function getMethod() {
    return $this->method;
  }
  
  function setAction($value) {
    $this->action = $value;
  }
  function getAction() {
    return $this->action;
  }
  
  function setName($value) {
  	$this->name = $value;
  }
  function getName() {
  	return $this->name;
  }
  
  function gotError() {
  	return isset($this->errormessage) && $this->errormessage != "";
  }
  
  function addErrorMessage($message) {
  	if ($this->errormessage != "") {
  		$this->errormessage .= " | ";
  	}
  	$this->errormessage .= $message;
  }
  
  function setErrorMessage($message) {
  	$this->errormessage = $message;
  }
  
  function getErrorMessage() {
  	return $this->errormessage;
  }
  
  function doValidate() {
  	foreach ($this->fields as $id => $obj) {
  		$obj->doValidate();
  		if ($obj->gotError()) {
  			$this->addErrorMessage($obj->getErrorMessage());
  		}
  	}
  }

}

?>